import json
import requests
from datetime import datetime, timedelta


class MySession(requests.Session):
    def request(self, *args, **kwargs):
        kwargs.setdefault('timeout', 5)
        return super(MySession, self).request(*args, **kwargs)

def lis_new(pid, start_time, end_time):
    
    headers = {
                "User-Agent":
                    "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36"
            }
    # 获取授权
    # url_auth = "http://10.68.60.145:8001/Clinician/FunsCL/ViewReport"
    url_auth = "http://10.68.60.145:8001/Clinician/FunsCL/ViewReport/user=5613/patno=%s/ward=5116/model=3/auth=07/mac=52-54-00-AA-D6-BE/ip=10-68-113-210/hostname=PC-AAD6BE" % pid
    # data_auth = {
    #     "user":"5613",
    #     "patno":"23097208",
    #     "ward":"5116",
    #     "model":"3",
    #     "auth":"07",
    #     "mac":"52-54-00-AA-D6-BE",
    #     "ip":"10-68-113-210",
    #     "hostname":"PC-AAD6BE"
    # }
    users = MySession()
    users.get(url_auth, headers=headers)
    # 获取检查列表
    url_post_report_list = "http://10.68.60.145:8001/Clinician/FunsCL/GetReport"

    post_data_report_list = {
        "searchflag":2,
        "dtBegin":start_time,
        "dtEnd":end_time,
        "deptcode":"5116",
        "patno":str(pid),
        "patid":None,
        "bedno":None,
        "patname":None,
        "wardcode":None,
        "barcode":None,
        "flagprint":2,
        "specimen":None,
        "idcard":None,
        "hoscode":None,
        "item":None,
        "inpid":None,
        "orino":None,
        "flagview":2,
        "jz":0,
        "wj":0,
        "self":0,
        "yg":0,
        "ny":0,
        "hj":0,

    }


    get_report_list = users.get(
        url_post_report_list,
        params=post_data_report_list,
        headers=headers
        )
    if get_report_list.status_code != 200:
        raise Exception('网络访问失败')
    get_report_list = get_report_list.json().get("datas")
    # 根据每条reportid获取检验详情
    url_report_details = "http://10.68.60.145:8001/Clinician/FunsCL/GetReportDetails"

    hyd = {}
    with open('.\\myjson\\lis_data.json', 'r', encoding='utf-8') as f:
        hyd_dic = json.load(f)
    patno = ''
    patname = ''
    pat_idcardno = ''
    pat_agestr =''
    pat_sex = ''
    req_bedno = ''

    req_dt = []
    s_time = datetime.strptime(start_time, "%Y-%m-%d")
    e_time = datetime.strptime(end_time, "%Y-%m-%d")
    if get_report_list:
        for each in get_report_list:
            report_dt = datetime.strptime(each.get('report_dt').split()[0], "%Y-%m-%d")
            if s_time<= report_dt <= e_time:
               
                reportid = each.get('reportid')
                rptunitid = each.get('rptunitid')
                
                rechkdt = each.get('rechk_dt')
                patno = each.get('pat_no')
                patname = each.get('pat_name')
                pat_idcardno = each.get('pat_idcardno')
                pat_agestr = each.get('pat_agestr')
                pat_sex = each.get('pat_sex')
                req_bedno = each.get('req_bedno')
                req_dt.append(each.get('req_dt'))
                # req_reason = each.get('req_reason')
                post_data_report_details = {
                    "reportid":reportid,
                    "rptunitid":rptunitid,
                    "rechkdt":rechkdt,
                    "patno":patno,
                    "patname":patname,
                    "mode":1,
                    "hisflag":None,
                }
                get_report_details = users.post(
                    url_report_details,
                    data=post_data_report_details,
                    headers=headers
                ).json()
             
                for result in get_report_details.get('results'):
                    rpt_itemname = result.get('rpt_itemname_show').strip("*")
                    result_str = result.get('result_str')
                    result_unit = result.get('result_unit')
                    result_flag = result.get('result_flag')
                    resultdt = result.get('resultdt').split()[0] if result.get('resultdt') else ''
                    
                    if rpt_itemname in ["白细胞计数", "红细胞计数"] and result_unit in ["个/uL", ]:
                        
                        continue
                    hyd_item = hyd_dic.get(rpt_itemname)
                    
                    if hyd_item:
                        
                        series = hyd_item['series']
                        if hyd.get(series) is None:
                            hyd[series] = {"results": [], "normal": True, "resultdt": resultdt,}  
                            
                        if result_flag in ["↑ 偏高", ] or result_str in ["阳性", "弱阳性"]:
                            flag = hyd_item['high']
                            hyd[series]["normal"]=False
                        elif result_flag in ["↓ 偏低", ] or result_str in ["阴性"]:
                            flag = hyd_item['low']
                            hyd[series]["normal"]=False
                        else:
                            flag = ""
                        hyd[series]["results"].append("{} {} {}{}".format(
                            rpt_itemname, result_str, result_unit, flag
                        ))
                    

    hyd_list = []
  
    sorted(req_dt, key=lambda d: datetime.strptime(d, "%Y-%m-%d %H:%M:%S").timestamp())
    for k, v in hyd.items():
        parts = "{}({})：{}".format(k, v["resultdt"], "，".join(v["results"]))
        if v["normal"] is True:
            parts += " 未见明显异常"
        hyd_list.append(parts)
    hyd_lis = "；".join(hyd_list)
        
    return  {
        "patno":pid,
        "patname":patname,
        "pat_agestr":pat_agestr,
        "pat_sex":pat_sex,
        "pat_idcardno":pat_idcardno,
        "req_bedno":req_bedno,
        "req_dt":req_dt[0] if req_dt else '',
        "lis":hyd_lis,
        }



if __name__ == "__main__":
    
    end_time = datetime.strftime(datetime.today(), "%Y-%m-%d")
    start_time = datetime.strftime(datetime.today()+timedelta(days=-30), "%Y-%m-%d")
    end_time = "2025-02-18"
    start_time ="2025-02-14"
    print(lis_new(25017583, start_time, end_time))